<?php

namespace App\Http\Controllers\Admin\UserManager;

use App\Enums\LabelEnum;
use App\Enums\RedisKeyEnum;
use App\Enums\FinancialEnum;
use App\Exceptions\BasicException;
use App\Services\Tools\RedisService;
use App\Http\Controllers\BaseController;
use App\Services\Tools\ContentService;
use App\Services\Tools\ExportService;
use App\Services\Tools\FrontHttpRequest;
use App\Services\Tools\HelperService;
use App\Services\Tools\ParamVerify;
use Illuminate\Http\Request;

//引用http请求类
use App\Response\Response;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class UserAccountController extends BaseController
{

    /**
     * @api {post} /user-manager/user-account/operate/add-exp 增加经验
     * @apiVersion 0.1.0
     * @apiName 会员管理-增加经验
     * @apiGroup 会员管理
     * @apiParam {int} id          用户id
     * @apiParam {float} exp          增加的经验值
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function AddExp(Request $request)
    {
        $v = app('validator')->make($request->all(),
            [
                'id' => 'required|integer',
                'exp' => 'required|numeric|max:7200000',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $params = $request->input();
        $userId = $params['id'];

        $userExp = app('model_user_exp')->getUserExp($userId);
        if ($params['exp'] + $userExp < 0) {
            throw new BasicException(0, "经验值不能减为负数");
        }

        $rows = app('repo_user')->addExp($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "增加经验失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {post} /user-manager/user-account/operate/reset-emchat 重置环信账号
     * @apiVersion 0.1.0
     * @apiName 会员管理-重置环信账号
     * @apiGroup 会员管理
     * @apiParam {int} id 用户id
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function ResetEmchat(Request $request)
    {
        $params = $request->input();
        $userId = $params['id'];

        $rows = app('repo_user')->resetEmChat($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "重置失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {post} /user-manager/user-account/operate/set-user-role 设置取消官方身份
     * @apiVersion 0.1.0
     * @apiName 会员管理-设置取消官方身份
     * @apiGroup 会员管理
     * @apiParam {number} id 用户id
     * @apiParam {number} type          1: 取消 2:设置
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function SetUserRole(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'id' => 'required|integer',
                'type' => 'required|numeric|in:1,2',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();
        $userId = $params['id'];

        $rows = app('repo_user')->setUserRole($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "取消/设置失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {post} /user-manager/user-account/ban 会员管理-封禁（改名并拆分出解封接口）
     * @apiVersion 0.1.0
     * @apiName 会员管理-封禁解封
     * @apiGroup 会员管理
     * @apiParam {number} user_id        用户id，必须
     * @apiParam {string} seal_time      封禁日期，y-m-d H:i:s，必须
     * @apiParam {string} remark         封禁理由，必须
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function ban(Request $request)
    {
        //参数校验
        /*$v = app('validator')->make($request->all(), [
            'user_id'    => 'required|integer',
            'seal_time' => 'required|date_format:"Y-m-d H:i:s"',
            'remark'    => 'required|string|max:255',
        ]);*/
        $v = app('validator')->make($request->all(), [
            'user_id'    => 'required|integer',
            'remark'    => 'required|string|max:255',//详情说明
            'seal_time_type' => 'required|integer|in:0,1,2,3',//0=永久;1=小时;2=天数;3=月
            'seal_time_int' => 'required|integer|min:0',//封禁数
            'source' => 'required|string|max:255',//封禁来源
            'reason' => 'required|string|max:255',//封禁原因
            'url' => 'required|array',//封禁证据
            'is_ban_auth' => 'required|integer|in:0,1'//封禁相关联实名认证账号;0=否;1=是
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $params = $request->input();
        $userId = $params['user_id'];
        $params['action'] = 1;

        /*if ($params['action'] == 1) {
            if (empty($params['seal_time']) || empty($params['remark'])) {
                throw new BasicException(10001, "参数不全");
            }
        }*/

        $rows = app('repo_user')->setBanUser($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "封禁失败！");
        }
        RedisService::clearUserInfo($userId);
        return Response::sendData(true);
    }

    /**
     * @api {post} /user-manager/user-account/unblock 会员管理-解封
     * @apiVersion 0.1.0
     * @apiName 会员管理-封禁解封
     * @apiGroup 会员管理
     * @apiParam {number} user_id        用户id，必须
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function unblock(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(), [
            'user_id'    => 'required|integer',
            'reason' => 'required|string|max:255',//封禁原因
            'url' => 'required|array',//封禁证据
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $params = $request->input();
        $userId = $params['user_id'];
        $params['action'] = 2;

        $rows = app('repo_user')->setBanUser($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "解封失败！");
        }
        RedisService::clearUserInfo($userId);

        return Response::sendData(true);
    }

    /**
     * @api {post} /user-manager/user-account/operate/give-gift 赠送礼物
     * @apiVersion 0.1.0
     * @apiName 会员管理-赠送礼物
     * @apiGroup 会员管理
     * @apiParam {number} id 用户id
     * @apiParam {number} number        礼物数量
     * @apiParam {number} gift_id       礼物id
     * @apiParam {string} remark        备注 （选填）
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function giveGift(Request $request)
    {
        //        throw new BasicException(0, '临时关闭');

        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id'  => 'required|integer',
                'number'  => 'required|numeric',
                'remark'  => 'string|max:200',
                'gift_id' => 'required|numeric|exists:mysql.ln_gift,id',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $params = $request->input();
        $userId = $params['id'];
        $params['admin_id'] = $request->admin_id;

        $rows = app('repo_user')->giveGift($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "充值失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {post} /user-manager/user-account/operate/recharge 用户充值
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户充值
     * @apiGroup 会员管理
     * @apiParam {number} id 用户id
     * @apiParam {number} type        类型 1：余额 2：收益 3：特殊币，必须
     * @apiParam {float}  money       金额，必须
     * @apiParam {string}  remark     充值备注，最多255个字符，必须
     * @apiParam {string}  purpose     充值目的，1：测试费用；2：24小时奖励；3：公会周奖励；4：公会月奖励；5：账号冲正；6：其它，必须
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function recharge(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id'  => 'required|integer',
                'money'  => 'required|numeric|max:10000000',
                'type'   => 'required|numeric|in:1,2',
                'remark' => 'string|max:200',
                'purpose' => 'required|integer|in:1,2,3,4,5,6',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $params = $request->input();
        $userId = $params['id'];
        $params['admin_id'] = $request->admin_id;
        $rows = app('repo_user')->userRecharge($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "充值失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {delete} /user-manager/user-account 用户删除
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户删除
     * @apiGroup 会员管理
     * @apiParam {string} ids                       字符串分割的id 必传
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function del(Request $request)
    {
        //参数校验
        try {
            $this->validate($request, [
                'ids' => 'required|string',
            ]);
        } catch (\Exception $e) {
            throw new BasicException(10001, json_encode($e->errors()));
        }

        $params = $request->input();
        $userIdArr = explode(",", $params['ids']);

        $userList = app("model_user")->whereIn("user_id", $userIdArr)->select(["user_id"])->get();
        $userIdList = empty($userList) ? [] : array_column($userList->toArray(), "user_id");
        if (count($userIdArr) != count($userIdList)) {
            throw new BasicException(10001, '存在不合法的用户id！');
        }

        $idsArr = $userIdList;

        $rows = app('repo_user')->delUserAccount($idsArr);
        if (!$rows) {
            throw new BasicException(10001, "删除失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {put} /user-manager/user-account 用户修改
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户修改
     * @apiGroup 会员管理
     * @apiParam {number} id 用户id
     * @apiParam {string} head_picture                      头像
     * @apiParam {number} user_code                         用户编号
     * @apiParam {number} nickname                          昵称
     * @apiParam {number} sex                               性别 1：男 2：女
     * @apiParam {string} real_name                         真实姓名
     * @apiParam {string} identity_number                   身份证号
     * @apiParam {string} birthday                          生日
     * @apiParam {string} signature                         签名
     * @apiParam {string} constellation                     星座
     * @apiParam {string} profession                        职业
     * @apiParam {number} gift_bag_id                       邀请礼包id
     * @apiParam {number} gift_bag_quantity                 邀请礼包数量
     * @apiSuccessExample 成功响应
     *      {"code":200,"data":true}
     * @apiError 10001 参数校验失败
     * @apiErrorExample 错误响应
     *      {
     *          "code": 10001,
     *          "message": "errorMsg"
     *      }
     */
    public function update(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'id'      => 'required|integer',
                'head_picture'      => 'filled|string',
                'user_code'         => 'required|numeric|integer|max:2100000000',
                'nickname'          => 'required|string|max:255 ',
                'sex'               => 'required|numeric|in:1,2',
                'real_name'         => 'filled|string|max:255',
                'identity_number'   => 'filled|string|max:255',
                'birthday'          => 'filled|string',
                'signature'         => 'filled|string|max:255',
                'constellation'     => 'filled|string|max:255',
                'profession'        => 'filled|string|max:255',
                'gift_bag_id'       => 'filled|numeric|min:0',
                'gift_bag_quantity' => 'filled|numeric|min:0|max:2100000000',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $params = $request->only([
            'id',
            'sex',
            'real_name',
            'identity_number',
            'birthday',
            'signature',
            'constellation',
            'profession',
            'head_picture',
            'user_code',
            'nickname',
            'gift_bag_id',
            'gift_bag_quantity',
            'intro_voice',      // 语音
            'user_photo',      // 照片墙
            'user_label',      // 交友标签
            'province_id',      // 省
            'city_id',      // 市
            'county_id',      // 区
            'vedio',      // 视频
        ]);

        $res = app('repo_user');
        $userId = $params['id'];

        $rows = $res->saveUserAccount($userId, $params);
        if (!$rows) {
            throw new BasicException(10001, "更新失败！");
        }

        return Response::sendData(true);
    }

    /**
     * @api {get} /user-manager/user-account/detail 用户详情数据
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户详情数据
     * @apiGroup 会员管理
     * @apiParam {number} id 用户id
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "user_id(用户id)": 642950,
     * "gift_bag_id(礼包id)": 18,
     * "gift_bag_quantity(礼包数量)": 0,
     * "user_data": {
     * "user_code(用户编号)": 359637,
     * "sex(性别)": 2,
     * "head_picture(头像)": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/default_avatar.png",
     * "nickname(昵称)": "改名测试",
     * "signature(签名)": "",
     * "birthday(生日)": "0000-00-00",
     * "constellation(星座)": "",
     * "profession(职业)": "",
     * "real_name(真实姓名)": "",
     * "identity_number(身份证号码)": "",
     * }
     * }
     * }
     */
    public function detail(Request $request)
    {
        $params = $request->only(['id']);
        //参数校验
        $v = app('validator')->make($params, [
            'id'      => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $userId = $params['id'];
        $list = app('repo_user')->getUserInfo($userId);

        return Response::sendData($list);
    }

    /**
     * @api {get} /user-manager/user-account 用户列表
     * @apiVersion 0.1.0
     * @apiName 会员管理-用户列表
     * @apiGroup 会员管理
     * @apiParam {number} has_gift_bag 含有礼包用户 0：不包含 1：包含 可选
     * @apiParam {number} sex 性别 1：男 2：女 可选
     * @apiParam {string} nickname 昵称 可选
     * @apiParam {string} mobile 用户电话号码
     * @apiParam {number} user_code 用户编号 可选
     * @apiParam {number} app_type 来源app 1气泡语音2气泡星球 可选
     * @apiParam {number} page 当前页数 可选
     * @apiParam {number} perPage 分页容量 可选
     * @apiSuccessExample 成功响应
     * {
     * "code": 200,
     * "data": {
     * "list": [
     * {
     * "user_id(用户id)": 642866,
     * "user_code(用户编号)": 111,
     * "user_no(邀请码)": 111,
     * "role(身份 1：正常 2：官方)": 1,
     * "room_id(房间id)": 123,
     * "head_picture(头像)": "https://yutangyuyin.oss-cn-hangzhou.aliyuncs.com/custom/default_avatar.png",
     * "mobile(用户手机)": "17630576610",
     * "nickname(用户昵称)": "空夏master",
     * "gift_bag_name(邀请礼包)": "补偿礼包2",
     * "gift_bag_quantity(礼包剩余数量)": 99999,
     * "gift_bag_id(礼包id)": 18,
     * "rank_id(会员等级)": 55,
     * "money(可用金币)": "13325968645354.00",
     * "coin(特殊币)": "0.00",
     * "earnings(收益)": "131833680.00",
     * "seal_time(封禁时间)": "",
     * "register_time(注册时间)": "2020-09-19 14:20:43",
     * "sex(性别)": 2,
     * "signature(签名)": "",
     * "birthday(生日)": "0000-00-00",
     * "constellation(星座)": "",
     * "profession(职业)": "",
     * "real_name(真实姓名)": "",
     * "identity_number(身份证号码)": "",
     * "exp(当前经验值)":45,
     * "app_type(来源app 1气泡语音2气泡星球)":1
     * "earnings_status(收益冻结状态：1：正常；0：被封禁)":1
     * }
     * ],
     * "meta": {
     * "page": 1,
     * "limit": 10,
     * "next": null,
     * "total": 1
     * }
     * }
     * }
     */
    public function list(Request $request)
    {

        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'has_gift_bag' => 'filled|numeric|in:-1,0,1',
                'mobile'       => 'string|max:11',
                'sex'          => 'filled|numeric|in:-1,1,2,0',
                'perPage'      => 'filled|numeric',
                'page'         => 'filled|numeric',
                'app_type'     => 'filled|numeric|in:-1,1,2',
                'status'    => 'filled|numeric|in:0,1,2',
                'user_type' => 'filled|integer|in:0,1,2,3',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $list = app('repo_user')->getUserAccountQueryList($request->input());

        $page = $list['current_page'];
        $limit = $list['per_page'];
        $next = $list['next_page_url'];
        $total = $list['total'];
        $returnList = [
            'code' => 200,
            'data' => [
                'list' => $list['data'],
                'meta' => [
                    'page'  => $page,
                    'limit' => $limit,
                    'next'  => $next,
                    'total' => $total,
                ],
            ],
        ];

        return json_encode($returnList);
    }

    /**
     * @api {Post} /user-manager/user-account/rechargeUserExport 导出充值用户
     * @apiGroup 补充接口-订单管理
     * @apiParam {String} start_time 开始时间（必须），yyyy-mm-dd hh:ii:ss
     * @apiParam {String} end_time 结束时间（必须），yyyy-mm-dd hh:ii:ss
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "download_url": "http://yutangyuyin1.oss-cn-hangzhou.aliyuncs.com/data_excel/20210602161610152充值新用户.xls"
     * }
     * }
     */
    public function rechargeUserExport(Request $request)
    {
        $startTime = $request->start_time;
        $endTime = $request->end_time;
        if (empty($startTime) || empty($endTime)) {
            throw new BasicException(0, '请选择开始和结束时间');
        }
        $list = app('repo_user_recharge')->getNewUserRecharge(strtotime($startTime), strtotime($endTime));
        $headings = [
            '用户编号',
            '昵称',
            '充值金额',
        ];

        return app('repo_export')->export(17, $request->all(), $headings, $list);
    }


    //查询所有用户id
    private function getUsers($registerTimeRange)
    {
        return app('model_user')
            ->select('user_id', 'user_no')
            ->with([
                'user_data' => function ($query) {
                    $query->select(['user_id', 'nickname']);
                },
            ])
            ->whereBetween('register_time', $registerTimeRange)
            ->where('deleted', 0)
            ->get()
            ->toArray();
    }


    /**
     * @api {Post} /user-manager/user-account/setEarningsStatus 冻结或解冻收益账户
     * @apiGroup 补充接口-用户管理-用户账号管理
     * @apiParam {String} user_id 用户id
     * @apiParam {String} freeze_reason 冻结原因，冻结账户的时候必传
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "earnings_status": 0 修改后的收益冻结状态：1：正常；0：被封禁
     * }
     * }
     */
    public function setEarningsStatus(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'user_id'       => 'required|integer',
                'freeze_reason' => 'string|max:30',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $userId = $request->user_id;
        $freezeReason = $request->freeze_reason;

        $user = app('model_user')->getInfo('earnings_status', ['user_id' => $userId]);
        if (empty($user)) {
            throw new BasicException(93046);
        }

        DB::beginTransaction();
        try {
            if ($user->earnings_status == 1) {
                $action = '冻结';
                $user->earnings_status = 0;

                if (empty($freezeReason)) {
                    throw new BasicException(0, '请填写冻结原因');
                }

                //1.给用户发送系统消息
                app("repo_user_news")->userNewsAdd([
                    'user_id'  => $userId,
                    'content'  => "您因{$freezeReason}原因，账户收益金额被冻结，请及时联系官方解除冻结",
                    'add_time' => time(),
                    'title'    => '账户收益',
                ]);

                //2.如果有正在提现的订单直接改为提现失败
                $withdrawRecords = app("model_user_withdraw")
                    ->select('id', 'gold', 'bank_type')
                    ->where('user_id', $userId)
                    ->where('platform_status', 1)
                    ->where('status',1)
                    ->get();
                $withdrawRecordIds = [];
                foreach ($withdrawRecords as $withdrawRecord) {
                    if (in_array($withdrawRecord->bank_type,[FinancialEnum::BANKCARD_WITHDRAW, FinancialEnum::COMPANY_WITHDRAW])) {
                        //修改提现状态
                        app('model_user_withdraw')
                            ->where('id', $withdrawRecord->id)
                            ->update([
                                'platform_status' => 3,
                                'status' => 3,
                                'audit_time' => time(),
                                'fail_reason' => "账户收益被冻结"
                            ]);
                    } else {
                        //修改提现状态
                        app('model_user_withdraw')
                            ->where('id', $withdrawRecord->id)
                            ->update([
                                'platform_status' => 3,
                                'status' => 3,
                                'audit_time' => time(),
                                'remark' => "账户收益被冻结"
                            ]);
                    }

                    //回退用户收益
                    app('repo_user')->serUserEarnings($userId, $withdrawRecord->gold, 1);
                    //更新资金日志
                    app('model_account_earnings_log')
                        ->where("source_id", $withdrawRecord->id)
                        ->where("change_type", 23)
                        ->update([
                            'change_desc' => '已退回',
                            'change_type' => 24,
                        ]);
                    $newBalanceInfo = app('repo_account')->getUserBalance($userId);
                    //收益变动时，可提现收益也需要变动
                    app('repo_account')->changeUserWithdrawableEarnings($userId, $withdrawRecord->gold, 1, 24, 1, $newBalanceInfo);
                    $withdrawRecordIds[] = $withdrawRecord->id;
                }

                //记录用户冻结收益的日志
                app('model_user_earnings_freeze_log')
                    ->add($request, "{$action}账户收益，原因：{$freezeReason}");
            } else {
                $action = '解冻';
                $user->earnings_status = 1;

                //1.给用户发送系统消息
                app("repo_user_news")->userNewsAdd([
                    'user_id'  => $userId,
                    'content'  => "恭喜您，账户收益金额已解冻",
                    'add_time' => time(),
                    'title'    => '账户收益',
                ]);

                //记录用户冻结收益的日志
                app('model_user_earnings_freeze_log')
                    ->add($request, "{$action}账户收益");
            }

            //修改用户账户收益状态
            app('model_user')->where('user_id', $userId)->update(['earnings_status' => $user->earnings_status]);

            //提现失败的记录通知财务系统
            if (isset($withdrawRecordIds) && $withdrawRecordIds) {
                // 推送到财务系统 financialSys
                $ids = implode(',', $withdrawRecordIds);
                app('repo_user_withdraw')->pushWithdrawDataToFinancialSys($ids);
            }

            DB::commit();

            return Response::sendData(['earnings_status' => $user->earnings_status]);
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $action . '失败：' . $e->getMessage());
        }
    }

    /**
     * @api {Post} /user-manager/user-account/setEarningsStatusOrMoney 冻结或解冻收益账户|凍結餘額或解凍
     * @apiGroup 补充接口-用户管理-用户账号管理
     * @apiParam {String} user_id 用户id
     * @apiParam {String} freeze_reason 冻结原因，冻结账户的时候必传
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "earnings_status": 0 修改后的收益冻结状态：1：正常；0：被封禁
     * }
     * }
     */
    public function setEarningsStatusOrMoney(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'user_id'           => 'required|integer',
                'freeze_reason'     => 'string|max:30',
                'seal_remark'       => 'string|max:30',
                'is_seal_money'     => 'string|integer|in:0,1',
                'earnings_status'   => 'string|integer|in:0,1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $userId = $request->user_id;
        $freezeReason = $request->freeze_reason;
        $sealRemark = $request->seal_remark;
        $isSealMoney = $request->is_seal_money;
        $earningsStatus = $request->earnings_status;

        $user = app('model_user')->getInfo(['earnings_status','is_seal_money'], ['user_id' => $userId]);
        if (empty($user)) {
            throw new BasicException(93046);
        }

        DB::beginTransaction();
        try {
//            if ($earningsStatus == 1) {
//                $action = '冻结';
//                $user->earnings_status = 0;
//
//                if (empty($freezeReason)) {
//                    throw new BasicException(0, '请填写冻结原因');
//                }
//
//                //1.给用户发送系统消息
//                app("repo_user_news")->userNewsAdd([
//                    'user_id'  => $userId,
//                    'content'  => "您因{$freezeReason}原因，账户收益金额被冻结，请及时联系官方解除冻结",
//                    'add_time' => time(),
//                    'title'    => '账户收益',
//                ]);
//
//                //2.如果有正在提现的订单直接改为提现失败
//                $withdrawRecords = app("model_user_withdraw")
//                    ->select('id', 'gold')
//                    ->where('user_id', $userId)->where('status', 1)
//                    ->get();
//                $withdrawRecordIds = [];
//                foreach ($withdrawRecords as $withdrawRecord) {
//                    //修改提现状态
//                    app('model_user_withdraw')
//                        ->where('id', $withdrawRecord->id)
//                        ->update(['platform_status' => 3, 'audit_time' => time(), 'remark' => "账户收益被冻结"]);
//                    //回退用户收益
//                    app('repo_user')->serUserEarnings($userId, $withdrawRecord->gold, 1);
//                    //更新资金日志
//                    app('model_account_earnings_log')
//                        ->where("source_id", $withdrawRecord->id)
//                        ->where("change_type", 23)
//                        ->update([
//                            'change_desc' => '已退回',
//                            'change_type' => 24,
//                        ]);
//                    $withdrawRecordIds[] = $withdrawRecord->id;
//                }
//
//                //记录用户冻结收益的日志
//                app('model_user_earnings_freeze_log')
//                    ->add($request, "{$action}账户收益，原因：{$freezeReason}");
//            } else {
//                $action = '解冻';
//                $user->earnings_status = 1;
//
//                //1.给用户发送系统消息
//                app("repo_user_news")->userNewsAdd([
//                    'user_id'  => $userId,
//                    'content'  => "恭喜您，账户收益金额已解冻",
//                    'add_time' => time(),
//                    'title'    => '账户收益',
//                ]);
//
//                //记录用户冻结收益的日志
//                app('model_user_earnings_freeze_log')
//                    ->add($request, "{$action}账户收益");
//            }

            // 凍結賬戶
            if ($isSealMoney == 1) {
                $action = '冻结';
                // 冻结账户
                if (empty($sealRemark)) {
                    throw new BasicException(0, '请填写冻结原因');
                }
                //1.给用户发送系统消息
                app("repo_user_news")->userNewsAdd([
                    'user_id'  => $userId,
                    'content'  => "您因{$sealRemark}原因，账户金额被冻结，请及时联系官方解除冻结",
                    'add_time' => time(),
                    'title'    => '账户金额',
                ]);
                //记录用户冻结收益的日志
                app('model_user_earnings_freeze_log')
                    ->add($request, "{$action}账户金额，原因：{$sealRemark}",2);
            } else {
                $action = '解冻';
                //1.给用户发送系统消息
                app("repo_user_news")->userNewsAdd([
                    'user_id'  => $userId,
                    'content'  => "恭喜您，账户金额已解冻",
                    'add_time' => time(),
                    'title'    => '账户金额',
                ]);
                //记录用户冻结收益的日志
                app('model_user_earnings_freeze_log')
                    ->add($request, "{$action}账户金额，原因：{$sealRemark}",2);
            }

            //修改用户账户收益状态
            app('model_user')->where('user_id', $userId)->update(
                [
//                    'earnings_status' => $earningsStatus,
                    'is_seal_money' => $isSealMoney
                ]
            );

            //提现失败的记录通知财务系统
//            if (isset($withdrawRecordIds) && $withdrawRecordIds) {
//                // 推送到财务系统 financialSys
//                $ids = implode(',', $withdrawRecordIds);
//                app('repo_user_withdraw')->pushWithdrawDataToFinancialSys($ids);
//            }

            DB::commit();

            return Response::sendData(['is_seal_money' => $isSealMoney],'修改成功');
        } catch (\Exception $e) {
            DB::rollBack();
            throw new BasicException(0, $action . '失败：' . $e->getMessage());
        }
    }

    /**
     * @api {Put} /user-manager/user-account/mobile 换绑手机号
     * @apiGroup 补充接口-用户管理-用户账号管理
     * @apiParam {String} user_id 用户id，必须
     * @apiParam {String} mobile 新手机号，必须
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200, 200表示成功，其它code都是失败
     * "data": []
     * }
     */
    public function editMobile(Request $request)
    {
        //参数校验
        $v = app('validator')->make($request->all(),
            [
                'user_id' => 'required|integer|min:1',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $userId = $request->user_id;
        $mobile = $request->mobile;

        $user = app('model_user')->getInfo('user_id', ['user_id' => $userId]);
        if (empty($user)) {
            throw new BasicException(93046);
        }

        $paramVerify = new ParamVerify();
        if ($paramVerify->mobile($mobile)->status == 0) {
            throw new BasicException(0, $paramVerify->msg);
        }
        $mobileExist = app('model_user')->getInfo('user_id', [['mobile', '=', $mobile], ['user_id', '<>', $userId]]);
        if ($mobileExist) {
            throw new BasicException(0, '手机号已经存在');
        }

        $user->mobile = $mobile;
        $res = $user->save();
        if ($res) {
            $reportData = [
                'source_id' => 0,
                'user_id'   => $userId,
                'mobile'    => $mobile ?? '',
            ];
            (new FrontHttpRequest())->reportUserInfo($reportData);

            //删除用户缓存
            app('redis')->del(sprintf(RedisKeyEnum::USER_INFO, $userId));

            return Response::sendData([]);
        } else {
            throw new BasicException(0, '换绑失败');
        }
    }

    /**
     * @api {put} /user-manager/user-account/alipay-num 修改支付宝账号个数
     * @apiGroup 补充接口-用户管理-修改支付宝账号个数
     * @apiParam {integer} user_id 用户id，必须
     * @apiParam {integer} alipay_acc_num 账号个数
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200, 200表示成功，其它code都是失败
     * "data": []
     * }
     */
    public function editAlipayUserNum(Request $request)
    {
        $data = $request->only(['user_id', 'alipay_acc_num']);
        $v = app('validator')->make($data,
            [
                'user_id'        => 'required|integer|min:1',
                'alipay_acc_num' => 'required|integer|min:1|max:10',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }
        $res = app('model_user')->where('user_id', $data['user_id'])->update(['alipay_acc_num' => $data['alipay_acc_num']]);
        return Response::sendData([]);
        /*if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '修改失败');
        }*/
    }

    /**
     * @Desc:修改银行卡数量
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/9/29 20:21
     */
    public function editBankUserNum(Request $request)
    {
        $data = $request->only(['user_id', 'bank_acc_num']);
        $v = app('validator')->make($data,
            [
                'user_id'        => 'required|integer|min:1',
                'bank_acc_num' => 'required|integer|min:1|max:10',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }
        $res = app('model_user')->where('user_id', $data['user_id'])->update(['bank_acc_num' => $data['bank_acc_num']]);
        return Response::sendData([]);
        /*
        if ($res) {
            return Response::sendData([]);
        } else {
            throw new BasicException(0, '修改失败');
        }*/
    }

    /**
     * @api {get} /user-manager/user-account/user-data 获取用户信息（ID、昵称等）
     * @apiVersion 3.6.3
     * @apiGroup 用户管理-用户账号管理
     * @apiParam {int} user_code 用户ID
     * @apiSuccessExample {json} Response-Example
     * {
    "code": 200,
    "data": {
    "user_code": 795365, 用户ID
    "nickname": "烟花易冷", 用户昵称
    "mobile": "" 手机号
    },
    "message": ""
    }
     */
    public function getUserData(Request $request)
    {
        $params = $request->only('user_code');
        $v = app('validator')->make($params, [
            'user_code' => 'required|integer|min:1|max:2100000000'
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        $userCode = $params['user_code'];

        //查询用户信息
        $userData = app('model_user_data')->getInfoByUserCode($userCode);

        return Response::sendData($userData);
    }

    /**
     * @api {get} /user-manager/user-account/user-money-data 用户数据列表
     * @apiVersion 3.0.1
     * @apiGroup 会员管理
     * @apiParam {integer} user_code 用户code，(选填)
     * @apiParam {string} nickname 用户昵称 （选填）
     * @apiParam {integer} sort 排序方式 升序1 降序2 (选填)
     * @apiParam {integer} order_by 根据什么排序  1 星愿排序 2气泡币排序 3收益排序(选填)
     * @apiParam {integer} perPage 页面尺寸(选填)
     * @apiParam {integer} page 页码(选填)
     * @apiSuccessExample {json} Response-Example
     * {
     * "code": 200,
     * "data": {
     * "total": 1,
     * "current_page": 1,
     * "last_page": 1,
     * "list": [
     * {
     * "user_id": 1318299,
     * "user_code（用户code）": 6203034,
     * "nickname（用户昵称）": "小气泡6203034",
     * "waterdrop_number（许愿流星数量）": 0,
     * "money（余额）": "5000.00",
     * "earnings（收益）": "0.00",
     * "update_at（更新时间）": "2021-11-22 10:14:50"
     * }
     * ]
     * },
     * "message": ""
     * }
     */
    public function userMoneyData(Request $request)
    {
        $data = $request->only(['user_code', 'nickname', 'sort', 'order_by', 'perPage', 'page']);
        $v = app('validator')->make($data,
            [
                'user_code' => 'filled|integer|min:1',
                'nickname'  => 'filled|string|min:1|max:32',
                'sort'      => 'filled|integer|in:1,2',//升序1 降序2
                'order_by'  => 'filled|integer|in:1,2,3',//1 星愿排序 2气泡币排序 3收益排序
                'perPage'   => 'filled|numeric|min:1',
                'page'      => 'filled|numeric|min:1',

            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }
        $data['perPage'] = $data['perPage'] ?? 20;
        $data['page'] = $data['page'] ?? 1;

        $result = app('repo_user')->userMoneyData($data);

        return Response::sendData($result);
    }

    public function sendNobility(Request $request)
    {
        $data = $request->only(['user_id', 'nobility_id', 'days']);
        $v = app('validator')->make($data,
            [
                'user_id'        => 'required|integer|min:1',
                'nobility_id'    => 'required|integer|min:1',
                'days'           => 'required|integer',
            ]);
        if ($v->fails()) {
            throw new BasicException(10001, $v->errors()->first());
        }

        app('repo_nobility_buy')->buyNobility($data['user_id'], $data['nobility_id'], $data['days']);

        return Response::sendData([], '赠送成功');
    }

    /**
     * 获取省市列表
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRegion()
    {
        $list = app("repo_user")->getRegionAll();

        return Response::sendData($list);
    }

    /**
     * 获取内容审核系统日志-用户处罚记录
     * @author zlh
     * @param  Request  $request
     * @param  $id int 用户id
     * @return string
     * @throws BasicException
     */
    public function getContentPunishList(Request $request)
    {
        $params = $request->only(['user_id']);
        //参数校验
        $v = app('validator')->make($params, [
            'user_id'      => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $userId = $params['user_id'];
        $service = new ContentService;
        $lists =$service->getPunishList(['user_id'=>$userId]);
        return Response::sendData($lists);
    }

    /**
     * 获取内容审核系统-用户处罚记录选项
     * @author zlh
     * @return string
     */
    public function getContentPunishOption()
    {
        $service = new ContentService;
        $lists =$service->getPunishOption();
        return Response::sendData($lists);
    }

    /**
     * 获取内容审核系统-用户时间记录选项
     * @author zlh
     * @return string
     */
    public function getContentTimeOption()
    {
        $service = new ContentService;
        $lists = $service->getPunishOption(2);
        return Response::sendData($lists);
    }

    /**
     * 获取用户行为详情列表
     * @author zlh
     * @return string
     */
    public function getActionLists(Request $request)
    {
        $params = $request->only(['user_id']);
        //参数校验
        $v = app('validator')->make($params, [
            'user_id'      => 'required|integer',
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }

        $userId = $params['user_id'];

        $list = app("repo_user")->actionLists($userId);
        return Response::sendData($list);
    }

    /**
     * 用户操作封禁
     * @author zlh
     * @param Request  $request
     * @return string
     */
    public function userActionSet(Request $request)
    {
        $params = $request->all();
        //参数校验
        $v = app('validator')->make($params, [
            'id'            => 'required|integer',
            'user_id'       => 'required|integer',
            'type'          => 'required|integer',      // 操作类型 1封禁 2解封
        ]);
        if ($v->fails()) {
            throw new BasicException(10001, getValidateMessage($v->messages()));
        }
        $result = app("repo_user")->userActionSet($params);
        return Response::sendData($result);
    }

    /**
     * 获取职业信息
     * @return string
     */
    public function getProfession()
    {
        $row = app("repo_config")->queryConfig('PROFESSION');
        $list = [];
        if (isset($row->value)) {
            $list = explode("\n", $row->value);
        }

        return Response::sendData($list);
    }

    //获取交友标签
    public function getFriendLabel()
    {
        $labelCateTitle = app('model_label_category')->where('id',LabelEnum::FRIEND)->where('state', 1)->pluck('name', 'id')->toArray();

        if(empty($labelCateTitle)){
            return Response::sendData([]);
        }
        $labelData= app('model_label')->where('category_id',LabelEnum::FRIEND)->where('state',1)->get(['id','name'])->toArray();

        return Response::sendData($labelData);
    }


    /**
     * @Desc:封禁/解封原因
     * @param  Request  $request
     * @return string
     * @throws BasicException
     * @author: shiquan
     * @Time: 2022/11/3 16:57
     */
    public function banReason(Request $request)
    {
        $params = $request->only(['type']);
        $validator= Validator::make($params, [
            'type' => 'required|integer|in:0,1',
        ]);
        if ($validator->fails()) {
            throw new BasicException(10001, $validator->errors()->first());
        }
        $list = app('repo_user')->banReason($params);
        return Response::sendData($list);
    }
}
